package com.zx.inf.sys.conf;

import com.zaxxer.hikari.HikariDataSource;
import com.zx.inf.sys.dao.InfDsInfoMapper;
import com.zx.inf.sys.entity.InfDsInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Component
public class DataSourceInit {

    @Autowired
    private InfDsInfoMapper infDsInfoMapper;

    @PostConstruct
    public void loadAllDataSource() {

        List<InfDsInfo> dsInfos = infDsInfoMapper.getAllDsInfo();
        for (InfDsInfo dsInfo : dsInfos) {
            HikariDataSource dataSource = createDataSource(dsInfo);
            DataSourceContextHolder.addDataSource(dsInfo.getId().toString(), dataSource);
        }
    }

    private HikariDataSource createDataSource(InfDsInfo dsInfo) {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(dsInfo.getDsUrl());
        dataSource.setUsername(dsInfo.getDsAccount());
        dataSource.setPassword(dsInfo.getDsPassword());
        if (dsInfo.getDsType() == 1) {
            dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        } else if (dsInfo.getDsType() == 2) {
            dataSource.setDriverClassName("ru.yandex.clickhouse.ClickHouseDriver");
        }
        return dataSource;
    }
}
